package qsl.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.*;

import android.text.InputFilter;
import android.text.Spanned;

public class string {
	public static void main(String[] args)
	{System.out.println("123".charAt(0));
		System.out.print(find("href=\"space.php?uid=2672176\"class=\"dropmenu\" onmou", "space.php?uid=(\\d+)"));
	}
	public static String format(String source, Object... params) {
		Matcher m = Pattern.compile("\\{(\\d+)\\}").matcher(source);
		while (m.find()) source = source.replace(m.group(0), String.valueOf(params[Integer.valueOf(m.group(1))]));
		return source;
	}
	public static String encode(String input) {
		return encode(input, "UTF-8");
	}
	public static String encode(String input, String encode){
		try { return URLEncoder.encode(input, encode); }
		catch (UnsupportedEncodingException e) { return ""; }
	}
	public static String decode(String input) {
		return decode(input, "UTF-8");
	}
	public static String decode(String input, String encode) {
		try { return URLDecoder.decode(input, encode); }
		catch (UnsupportedEncodingException e) { return ""; }
	}
	public static String find(String input, String regex){
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(input);
		while (m.find()) return m.group(1);
		return "";
	}
	public static String join(String[] strings, String separator) {
		StringBuffer buffer = new StringBuffer();
		for(String string: strings) {
			buffer.append(separator);
			buffer.append(string);
		}
		return buffer.toString().substring(separator.length());
	}
	public static InputFilter getIpFilter() {
		return new InputFilter() {
	    	@Override
	        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
	            if (end > start) {
	                String destTxt = dest.toString(),
	                	last = source.subSequence(start, end).toString(),
	                	resultingTxt = destTxt.substring(0, dstart) + last + destTxt.substring(dend);
	                
	                if (!resultingTxt.matches ("^\\d{1,3}(?:\\.(?:\\d{1,3}(?:\\.(?:\\d{1,3}(?:\\.(?:\\d{1,3})?)?)?)?)?)?")) { 
	                    return "";
	                } else {
	                	String[] splits = resultingTxt.split("\\.");
	                	for (int i = 0; i < splits.length; i++) {
	                		if(splits[i].length() == 3) {
	                			if (Integer.valueOf(splits[i]) > 255) return "";
	                			if (i == splits.length - 1) return i == 3 ? last : (last +  (last == "." || dstart < destTxt.length() ? "" : "."));
	                		}
	                	}
	                }
	            }
	            return null;
	        }
	    };
	}
}














